package com.ai.zhly.util.sms.client;

import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import com.ai.zhly.util.sms.msg.Msg_Cmpp_Connect;
import com.ai.zhly.util.sms.utils.Constant;
import com.ai.zhly.util.sms.utils.MakeMessage;

/**
 * 
 * @company：AsiaInfo BDX-DS-PSO NFJD/XZ/GD Dept.-GZ
 * @author：xw.jiang on 2015年11月13日
 * @email:jiangxw@asiainfo.com
 * @description:短信发送服务层
 */
public class SPClient {
	static Logger logger = Logger.getLogger(SPClient.class.getName());
	private static Socket sc;
	private static SPConnector conn;

	/**
	 * 测试入口
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		SPClient client = new SPClient();
		List<String> tellist = new ArrayList<String>();
		tellist.add("18260902572");
		String msg = "旅游大数据平台测试短信 123 xwjiang";
		client.sendMsgList(tellist, msg);
	}

	/**
	 * 登录状态 1) 没有登录/登录失败：-1 2) 登录成功：0
	 */
	public static int state = -1;

	/**
	 * 是否需要重启启动线程去处理接收和链接检测 需要：-1 不需要：0 (已经启动)
	 */
	public static int p = -1;

	/**
	 * 
	 * @param telList
	 * @param content
	 * @return
	 * 
	 */
	public boolean sendMsgList(List<String> telList, String content) {
		for (String tel : telList) {
			startSP(tel, content);
		}
		return true;
	}

	// 指定端口上启动服务器
	public int startSP(String telNum, String content) {
		boolean flag = (telNum.equals("") || telNum == null
				|| content.equals("") || content == null);
		if (!flag) {
			Constant.MOBILE = telNum;
			Constant.MSG_CONTENT = content;
			logger.info("[telphone:" + telNum + " && content:" + content + "]");
		} else {
			logger.info("电话号码和告警内容为空,短信发送失败");
			return -1;
		}
		try {
			if (state != 0) {
				sc = new Socket(Constant.IP, Constant.PORT);
				this.setSc(sc);
				conn = new SPConnector(sc);
				Msg_Cmpp_Connect cmpp_connect = MakeMessage
						.getCmpp_Connect(Constant.SPID, Constant.SPPWD);
				state = conn.connect(cmpp_connect);
			}
			if (state == 0) {
				conn.sendMessage();
			}
		} catch (Exception ef) {
			ef.printStackTrace();
			this.closeSP();
		}
		return state;
	}

	public SPConnector getConn() {
		return conn;
	}

	public Socket getSc() {
		return sc;
	}

	public void setSc(Socket sc) {
		SPClient.sc = sc;
	}

	public void setConn(SPConnector conn) {
		SPClient.conn = conn;
	}

	public SPClient() {
		super();
	}

	/**
	 * 
	 */
	public void closeSP() {
		try {
			SPClient.state = -1;
			SPClient.p = -1;
			SPClient.sc.close();
			conn.closeConnect();
		} catch (IOException e) {
			logger.info("登录状态：" + (state == 0 ? "成功" : "失败"));
			e.printStackTrace();
		}
	}

}
